<?php

// @formatter:off
/**
 * @file page.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: page.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/extensions/AutoTagger/autotagger/page.php $
 */
// @formatter:on

require_once WC_E_AUTOTAGGER_ROOTDIR."/includes/AutoTagger.php";

class ActionControllerAutotaggerPage extends WCActionController {
	//
	// Public methods.
	public function check() {
		$check = parent::check();

		if($check == WC_HTTPERROR_OK) {
			global $wcProfile;

			if(!$wcProfile->allowedTo(WC_PERM_AUTOTAGGER)) {
				global $errno;
				global $error;

				$check = WC_HTTPERROR_FORBIDDEN;
				$errno = $check;
				$error = "You have not enough privileges";
			}
		}

		return $check;
	}
	//
	// Protected methods.
	protected function subRun() {
		$ok = true;
		//
		// Loading global pointers.
		global $wcGroup;

		$holder = WCDirectoriesHolder::I();
		$autoTagger = AutoTagger::I();

		$autoTagger->cleanDeads();

		$items = $holder->itemsByGroup($wcGroup);
		uasort($items, "WCDirectory::NameSort");
		$directories = array();
		foreach($items as $directory) {
			if($directory->ok()) {
				$directories[$directory->id] = array(
					"id" => $directory->id,
					"name" => $directory->name,
					"tags" => array()
				);
				foreach($autoTagger->directoryTags($directory) as $tag) {
					$directories[$directory->id]["tags"][] = array(
						"id" => $tag->id,
						"name" => $tag->name
					);
				}
			}
		}

		$this->_manager->directories = $directories;
		$this->_manager->WC_E_AUTOTAGGER_script = WC_E_AUTOTAGGER_URI."/script.js";

		return $ok;
	}
	protected function subRunPOST() {
		$holder = WCDirectoriesHolder::I();
		$autoTagger = AutoTagger::I();

		$autoTagger->cleanDeads();

		$original = array();
		foreach($_POST as $key => $value) {
			if(preg_match("/original_([0-9]*)/", $key, $match)) {
				$original[$match[1]] = $value;
			}
		}
		$directories = array();
		foreach($_POST as $key => $value) {
			if(preg_match("/directory_([0-9]*)/", $key, $match) && $value != $original[$match[1]]) {
				$aux = array(
					"id" => $match[1],
					"tags" => explode(",", str_replace(",", ",     ", $value)),
					"object" => $holder->item($match[1])
				);
				array_walk($aux["tags"], create_function('&$val', '$val = trim($val);'));
				$aux["tags"] = array_filter($aux["tags"]);

				$directories[] = $aux;
			}
		}

		foreach($directories as $directory) {
			$autoTagger->updateDirectory($directory["object"], $directory["tags"]);
		}

		$this->subRun();
	}
}
